import { Component, EventEmitter, OnInit, Output, Input } from '@angular/core';
import { FormBuilder, FormGroup, Validators, ValidatorFn, ValidationErrors } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { NzMessageService } from 'ng-zorro-antd';
import { I18nService } from '../../../../../core/i18n/i18n.service';
import { RegionNumber } from '../../../../../model';
import { RegisterFormData } from '../../model/form.data';
import { MemberService } from 'src/app/routes/member-center/member.server';

@Component({
  selector: 'app-register-body-account',
  templateUrl: './register-body-account.component.html',
  styleUrls: ['./register-body-account.component.scss']
})
export class RegisterBodyAccountComponent implements OnInit {



  nzSelectedIndex = 0;
  emailForm: FormGroup;
  phoneForm: FormGroup;
  regionNumbers: RegionNumber[] = [];
  serviceError = true;
  isLoding=false;

  @Output()
  fromSubmit = new EventEmitter<RegisterFormData>();

  @Input()
  errorMsg: string;

  constructor(
    private fb: FormBuilder,
    private router: Router,
    private routes: ActivatedRoute,
    private i18nService: I18nService,
    private memberServer: MemberService,
    private message: NzMessageService
  ) {
    this.initForm();
    // this.initRouteParam();
  }

  toNext(type: number) {
    const map = new Map<Number, () => void>();
    map.set(1, this.toEmailNext);
    map.set(2, this.toPhoneNext);
    map.get(type).apply(this);
  }

  ngOnInit() {
    this.initRegionNumbers();

  }


  private toPhoneNext() {
    // tslint:disable-next-line:forin
    for (const key in this.phoneForm.controls) {
      this.phoneForm.controls[key].markAsDirty();
    }
    const data = this.phoneForm.value as {
      phone: string;
      regionNumber: string;
    };
    this.fromSubmit.next({
      type: 2,
      phone: data.phone,
      regionNumber: data.regionNumber
    });
  }

  private toEmailNext() {
    // tslint:disable-next-line:forin
    for (const key in this.emailForm.controls) {
      this.emailForm.controls[key].markAsDirty();
    }
    const data = this.emailForm.value as {
      email: string;
    };
    this.fromSubmit.next({
      type: 1,
      email: data.email,
    });
  }


  private initRegionNumbers() {
    this.i18nService.getRegionNumbers().subscribe(res => {
      if (res.status === 0) {
        this.regionNumbers = res.data;
      } else {
        this.message.create('error', res.message);
      }
      if (!this.regionNumbers || this.regionNumbers.length === 0) {
        this.message.create('warning', 'region numbers is empty');
      } else {
      }
    }, error => this.message.create('error', JSON.stringify(error)));
  }

  private validatorLoginId(f: FormGroup): void {
    if (f.valid) {
      const data = f.value.regionNumber + '-' + f.value.phone;
      this.getValidatorLoginId('校验账号是否重复',data)
    }
  }
  private validatorEmailLoginId(f: FormGroup): void {
    if (f.valid) {
      this.getValidatorLoginId('校验账号是否重复',f.value.email)
    }
  }
  async getValidatorLoginId(url,data){
    this.isLoding=true;
    let tag = await this.memberServer.getAJX(url,{loginId:data});
    this.memberServer.getApiSuccess(tag,{bool:true,msg:'此账号可注册'}) ? this.serviceError=false : this.restPhoneForm()  ;
    this.isLoding=false;
  }
  private restPhoneForm():void{

    this.serviceError=true;
    this.phoneForm.reset({phone:'',regionNumber:86});
    this.emailForm.reset();
  }
  changeTab(type){
    if(!this.isLoding){
      this.nzSelectedIndex = type;
      this.restPhoneForm();
    }
  };

  private initForm() {
    this.emailForm = this.fb.group({
      email: [null, [Validators.required, Validators.pattern('^[a-zA-Z0-9_\-]{2,}@[a-zA-Z0-9_\-]{2,}(\.[a-zA-Z0-9_\-]+){1,2}$')]],
    });
    this.phoneForm = this.fb.group({
      phone: [null, [Validators.required, Validators.pattern(/^1[34578]\d{9}$/)]],
      regionNumber: [86, [Validators.required]],
    });
  }


}

